using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

// 添加Ocelot配置文件
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);

// 添加服务到容器
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// 添加Ocelot服务
builder.Services.AddOcelot();

// 配置日志
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.SetMinimumLevel(LogLevel.Information);

// 添加CORS支持
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

var app = builder.Build();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// 使用CORS
app.UseCors("AllowAll");

// 使用授权
app.UseAuthorization();

// 映射控制器
app.MapControllers();

// 输出启动信息
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("=== Ocelot API Gateway Starting ===");
logger.LogInformation("Gateway URL: http://localhost:5200");
logger.LogInformation("User Service Route: /api/user/* -> http://localhost:5006/api/*");
logger.LogInformation("Product Service Route: /api/product/* -> http://localhost:5233/api/*");
logger.LogInformation("========================================");

// 启动Ocelot网关
try
{
    await app.UseOcelot();
}
catch (Exception ex)
{
    logger.LogError(ex, "Failed to start Ocelot Gateway");
    throw;
}

app.Run();
